#include <iostream>
#include<string>
#include<memory>
#include"Protocol.hpp"
#include"Socket.hpp"
#include"InetAddr.hpp"
using namespace socket_ns;
using namespace protocol_ns;
void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"<< std::endl;
}
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    std::unique_ptr<Socket> client = std::make_unique<TcpSocket>();

    InetAddr serveraddr(serverip,serverport);
    bool res = client->BulidClientSocket(serveraddr);
    Factory factory;
    std::string inbuffer;
    while(res)
    {
        //构建一个请求
        auto req = factory.BulidRequest();

        //序列化
        std::string send_str;
        req->Serialize(&send_str);
        std::cout << "Serialize: \n"<< send_str << std::endl;
        //能直接发吗？还要保证完整性——添加长度报头
        send_str = Encode(send_str);//len\r\n{    }\r\n
        std::cout << "Encode: \n"<< send_str << std::endl;
        //发送
        client->Send(send_str);

        //发完等server端发过来(对应答进行读取/收数据)
        int n = client->Recv(&inbuffer);
        if(n<=0)
        {
            break;
        }
        //保证应答的完整性
        std::string package = Decode(inbuffer);
        if(package.empty())
            continue;
        
        //收到完整应答
        auto resp = factory.BulidResponse();
        //反序列化
        resp->DeSerialize(package);
        std::cout<<resp->_result<<"["<<resp->_code<<"]"<<std::endl;

    }
    return 0;
}